package org.gdstash.ui.font;

import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;

public class FontSamplePanel extends JPanel {
    private Font font;
    private String sampleString;

    public FontSamplePanel(final String sampleString) {
        this.sampleString = sampleString;
    }

    public void setSampleFont(final Font font) {
        this.font = font;
        this.repaint();
    }

    public void paintComponent(final Graphics g) {
        super.paintComponent(g);
        if (this.font == null) {
            return;
        }
        final Graphics2D g2d = (Graphics2D) g;
        final FontRenderContext frc = g2d.getFontRenderContext();
        final TextLayout layout = new TextLayout(this.sampleString, this.font, frc);
        final Rectangle2D bounds = layout.getBounds();
        final int width = (int) Math.round(bounds.getWidth());
        final int height = (int) Math.round(bounds.getHeight());
        final int x = (this.getWidth() - width) / 2;
        final int y = height + (this.getHeight() - height) / 2;
        layout.draw(g2d, (float) x, (float) y);
    }
}
